package com.cb.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cb.mapper.TUserMapper;
import com.cb.service.UserService;
import com.jia.dto.LoginDto;
import com.jia.dto.ZhentaoException;
import com.jia.entity.User;
import com.jia.vo.LoginVo;
import com.jia.vo.ResultCodeEnum;
import com.jia.vo.UserInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private TUserMapper userMapper;
    @Override
    public boolean getCode(String phone, Map<String, Object> map) {
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5tEuAxSuHHnqCpW8LfK2","VyM1I8aClzm2hSxJf6k1FIOroVXSOv");
        //发起 客户端
        IAcsClient client = new DefaultAcsClient(profile);
        //设置短信发送的信息 签名 手机号码 验证码
        CommonRequest request=new CommonRequest();
        //设置请求方式
        request.setSysMethod(MethodType.POST);
        //设置阿里云节点
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //设置手机号码 设置成自己的
        request.putQueryParameter("PhoneNumbers",phone);
        //设置签名
        request.putQueryParameter("SignName","学习是一种生活习惯");
        //设置模板
        request.putQueryParameter("TemplateCode","SMS_180348176");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response=client.getCommonResponse(request);
            System.out.println(response);
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return false;
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        //根据手机号和验证码进行判断
        if (StrUtil.isBlank(loginDto.getPhone()) || StrUtil.isBlank(loginDto.getCode())) {
         throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }
        String phone = loginDto.getPhone();
        String code = loginDto.getCode();

        if (StrUtil.isBlank(redisTemplate.opsForValue().get(phone + "_" + code))){
            throw new ZhentaoException(ResultCodeEnum.CAPTCHA_ERROR);
        }
        //正确以后生成token保存到redis
        String token = IdUtil.simpleUUID().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(phone), 30, TimeUnit.DAYS);
        LoginVo loginVo = new LoginVo();
        //设置token
        loginVo.setToken(token);
        //设置refresh_token
        loginVo.setRefreshToken(":");
        //返回
        return loginVo;
    }

    @Override
    public UserInfo getUserInfo(String token){
        //        数据校验
        if (StrUtil.isBlank(token)) {
            throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
        }
        String Info = redisTemplate.opsForValue().get("user:login:" + token);
        System.out.println(Info);
        Info=Info.replace("\"","");
        //数据校验
        if (StrUtil.isBlank(Info)) {
            throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }
        QueryWrapper<User> qw = new QueryWrapper();
        qw.eq("phone",Info);

        User userInfo1 = userMapper.selectOne(qw);
        System.out.println("用户注册实名信息"+userInfo1);
        UserInfo userInfo = new UserInfo();
        if(userInfo1 == null){
            userInfo.setPhone(Info);
            return userInfo;
        }else{
            BeanUtils.copyProperties(userInfo1, userInfo);
            return userInfo;
        }
    }

    @Override
    public boolean register(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public User getOne(QueryWrapper<User> queryWrapper) {
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateByPhone(User user) {
        userMapper.updateByPhone(user);
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }
}
